package ribbon;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import java.util.List;

/**
 * @Description 每个服务轮询访问3次
 * @Author junjun Wang
 * @Date Create in 11:52 2023/12/7
 **/
public class DefinedRubbionRule extends AbstractLoadBalancerRule {

	private Integer total = 0;

	private Integer currentIndex = 0;

	private static final Integer maxCount = 3;

	public Server choose(ILoadBalancer lb) {
		if (lb == null) {
			return null;
		} else {
			Server server = null;

			while (server == null) {
				if (Thread.interrupted()) {
					return null;
				}
				// 获取当前可达服务
				List<Server> upList = lb.getReachableServers();
				// 获取所有服务
				List<Server> allList = lb.getAllServers();
				if (allList.isEmpty() || allList.isEmpty()) {
					return null;
				}
				// 从所有可用服务中随机获取一个，且每个服务被调用5次
				int index = getServiceIndex(upList.size());
				server = upList.get(index);
				if (server == null) {
					Thread.yield();
				} else {
					if (server.isAlive()) {
						return server;
					}
					server = null;
					Thread.yield();
				}
			}

			return server;
		}
	}

	private int getServiceIndex(Integer upListSize) {
		if (total < maxCount) {
			total++;
			return currentIndex;
		}
		total = 0;
		if (currentIndex == upListSize - 1) {
			currentIndex = 0;
			return currentIndex;
		}
		total++;
		return ++currentIndex;
	}

	public Server choose(Object key) {
		return this.choose(this.getLoadBalancer());
	}

	@Override
	public void initWithNiwsConfig(IClientConfig iClientConfig) {

	}

}
